#-*-coding:utf-8-*-
# Create your views here.
from models import Wellcome_mail,Projects,Salesperson
from django.shortcuts import get_object_or_404,render_to_response
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.core.paginator import Paginator, InvalidPage
from crm.models import Members
from crm.models import Salesperson
from crm.models import Maillist,Maillog,Mailfile
from crm.jsondata import JsonResponse
import time,datetime
from django.conf import settings

import os
import email
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import Encoders
import smtplib

"""保存信息"""
def save (request):
    try:
        user_id=int(request.session['id'])
    except:
        return HttpResponseRedirect('/')
    if request.method == 'POST':
            new_data = request.POST.copy()
            autosendmail_value=request.POST.get('autosendmail','0')
            file_obj=request.FILES.get('mailfile', None)
            try:
                sales_obj=Salesperson.objects.get(pk=user_id)
            except:
                return HttpResponse('no sales info')

            if request.session['level']=="administrators" and new_data['wmid']!='':
                #管理员只修改
                wm=Wellcome_mail.objects.get(pk=int(new_data['wmid']))
                wm.program_id=int(new_data['p_id'])
                wm.title=new_data['title'].strip()
                wm.maincontent=new_data['maincontent'].strip()
                wm.thanks=new_data['thanks'].strip()
                wm.address=new_data['address'].strip()
                wm.site=new_data['site'].strip()
                wm.autosendmail=autosendmail_value
            else:
                try:
                    wm=Wellcome_mail.objects.get(program__pk=int(new_data['p_id']),sales=sales_obj)
                    wm.title=new_data['title'].strip()
                    wm.maincontent=new_data['maincontent'].strip()
                    wm.thanks=new_data['thanks'].strip()
                    wm.address=new_data['address'].strip()
                    wm.site=new_data['site'].strip()
                    wm.autosendmail=autosendmail_value
                except:
                    wm=Wellcome_mail(
                    program_id=int(new_data['p_id']),
                    title=new_data['title'].strip(),
                    maincontent=new_data['maincontent'].strip(),
                    thanks=new_data['thanks'].strip(),
                    address=new_data['address'].strip(),
                    site=new_data['site'].strip(),
                    sales=sales_obj,
                    autosendmail=autosendmail_value,
                    )
            wm.save()
            if file_obj:
                from os.path import basename
                shellpath=str(settings.WEB_ROOT)
                fileName=file_obj['filename']
                filetype=basename(fileName).split(".").pop().lower()
                fn=basename(fileName).split(".")[0].lower()
                fname=str(fn)+"_"+str(sales_obj.name)+"_"+str(wm.id)+"_at"
                filepath=str(settings.WEB_ROOT)+"/static/mailfile/"
                filepath=filepath.replace('//', '/')
                fileurl_value="/static/mailfile/"+str(fname)+'.'+filetype
                im=file(filepath+str(fname)+'.'+filetype,'wb')
                im.write(request.FILES.get('mailfile')['content'])
                im.close()
                wm.fileurl=fileurl_value
                wm.save()
    return HttpResponseRedirect('/wmlist/')

#添加新邮件
def saveaddmail (request):
    try:
        user_id=int(request.session['id'])
        sales_obj=Salesperson.objects.get(pk=user_id)
    except:
        return HttpResponseRedirect('/')
    output={}
    output['outhtml']=""
    output['havein']=0
    if request.method == 'POST':
        new_data = request.POST.copy()
        mailaddress=request.POST.get('mailaddress','')
        try:
            have_in=Maillist.objects.get(tomail=mailaddress,sales=sales_obj)
            output['errinfo']='The mailing list have a same mail'
            output['havein']=1
        except:
            members_obj=Members(
            id=0,
            )
            maillist_obj=Maillist(
            members=members_obj,
            sales=sales_obj,
            addtime=datetime.datetime.now(),
            sendtime=datetime.datetime.now(),
            tomail=mailaddress,
            subject='',
            mailbody='',
            issend=1,
            )
            maillist_obj.save()
            #output['outhtml']='Add success'

    #更新邮箱列表,并以HTML形式返回.
    mail_list=Maillist.objects.filter(sales=sales_obj).order_by('-id')
    output['outhtml']+="<table width='80%' class='grid' cellspacing='1' align='center'><tr><td colspan='10' class='title' align='center'>Your sending mail list&nbsp;<input type='button' class='button' name='editsubmit' onclick=\"showbox('addbox')\"  id='addsubmit' value='Add mail address'  /></td></tr>"
    output['outhtml']+="<tr valign='middle' align='left'>"
    output['outhtml']+="<td class='odd' width='15%'>ID</td>"
    output['outhtml']+="<td class='even' width='20%'>customer name</td>"
    output['outhtml']+="<td class='odd' width='30%'>to email</td>"
    output['outhtml']+="<td class='even' width='15%'>Edit</td>"
    output['outhtml']+="<td class='odd' width='10%'>On list</td>"
    output['outhtml']+="<td class='even' width='10%'>Delete</td>"
    output['outhtml']+="</tr>"

    for m in mail_list:
        output['outhtml']+="<span id=\"onemail"+str(m.id)+"\">"
        output['outhtml']+="<tr valign='middle' align='left'>"
        output['outhtml']+="<td class='odd'>"+str(m.id)+" <span id=\"mm"+str(m.id)+"\"></span></td>"
        try:
            output['outhtml']+="<td class='even'>"+str(m.members.name)+"</td>"
        except:
            output['outhtml']+="<td class='even'>&nbsp;</td>"
        output['outhtml']+="<td class='odd'><span id='cmail'"+str(m.id)+"'>"+str(m.tomail)+"</span></a></td>"
        output['outhtml']+="<td class='even' >"
        output['outhtml']+="<a href=\"javascript:editmail("+str(m.id)+",'"+str(m.tomail)+"')\">"
        output['outhtml']+="<img src=\"/static/images/icon_edit.gif\" /></a></td>"
        output['outhtml']+="<td class='odd'><a href=\"javascript:onsending("+str(m.id)+");\">"
        output['outhtml']+="<span id=\"on"+str(m.id)+"\">"
        if m.issend:
            output['outhtml']+="<img src=\"/static/images/yes.gif\" />"
        else:
            output['outhtml']+="<img src=\"/static/images/no.gif\" />"
        output['outhtml']+="</span></a></td>"
        output['outhtml']+="<td class='even' ><a href=\"javascript:delmail("+str(m.id)+");\" >"
        output['outhtml']+="<img src=\"/static/images/no.gif\" /></a></td>"
        output['outhtml']+="</tr></span>"

    output['outhtml']+="<tr><td  class='even' colspan='10' align='right'>"
    output['outhtml']+="</td></tr>"
    output['outhtml']+="</table>"
    output['outhtml']=output['outhtml'].replace('\n', '<br />') or ''

    return JsonResponse(output)
    #return HttpResponse(output['outhtml'])

def delatmailfile (request,mid=''):
    try:
        user_id=int(request.session['id'])
    except:
        return HttpResponseRedirect('/')
    output={}
    try:
        wm=Wellcome_mail.objects.get(pk=int(mid))
        try:
            from os.path import basename
            shellpath=str(settings.WEB_ROOT)
            c='rm '+shellpath+str(wm.fileurl)
            os.system(c)
        except:
            pass
        wm.fileurl=''
        wm.save()
        output['mid']=mid
    except:
        pass
    return JsonResponse(output)


"""mail列表"""
def list(request,page='1'):
    try:
        user_id=int(request.session['id'])
    except:
        return HttpResponseRedirect('/')
    """
    按所属SALES显示,管理员则可查看所有
    """
    if request.session['level']=="administrators":
        wm = Wellcome_mail.objects.order_by('id')
    else:
        wm = Wellcome_mail.objects.filter(sales__pk=user_id)
    return render_to_response('wmlist.html',{'wm':wm})

"""调用修改显示页"""
def info(request,wm_id=""):
    try:
        user_id=int(request.session['id'])
    except:
        return HttpResponseRedirect('/')
    pj = Projects.objects.order_by('id')
    if wm_id:
        wm = get_object_or_404(Wellcome_mail, pk=wm_id)
        return render_to_response('wmail_info.html',{'wm': wm,'pj':pj})
    else:
        return render_to_response('wmail_info.html',{'pj':pj})


"""删除"""
def del_wm (request,wm_id=""):
    try:
        user_id=int(request.session['id'])
    except:
        return HttpResponseRedirect('/')
    try:
        wm=Wellcome_mail.objects.get(pk=int(wm_id))
    except:
        return HttpResponse('error')
    if request.session['level']!="administrators":
        if int(wm.sales.id)!=int(user_id):
            return HttpResponse('The mail is not belong you')
    Wellcome_mail.objects.filter(pk=wm_id).delete()
    return HttpResponseRedirect('/wmlist/')

"""mail demo"""
def mdemo(request,wm_id=""):
    try:
        user_id=int(request.session['id'])
    except:
        return HttpResponseRedirect('/')
    try:
        wm=Wellcome_mail.objects.get(pk=wm_id)
    except:
        return HttpResponseRedirect('/wmlist/')
    from django.template import Template, Context
    t = Template('<SPAN lang=EN-US style="FONT-FAMILY: 新細明體; mso-font-kerning: 0pt; mso-bidi-font-family: 新細明體;FONT-SIZE: 10pt; COLOR: navy; FONT-FAMILY: Arial; mso-font-kerning: 0pt"><p>Dear (Customers\'name),</p>{{wm.maincontent|escape|linebreaks}}<p>Should you have any queries, please do not hesitate to contact me at (sales\'s tel) or email at (sales\'s email)</p>{{wm.thanks|escape|linebreaks}}<p>Best regards,<br/>(sales\'s truename)</p>{{wm.address|escape|linebreaks}}<p>Email:<a href="mailto:sales\'s email"><span >sales\'s email</span></a></p><p>Website:<a href="{{wm.site}}" >{{wm.site}}</a></p></span>')
    return HttpResponse(t.render(Context({'wm': wm})) )



def ajaxaddmail (request,cid):
    err=''
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    try:
        sales_obj=Salesperson.objects.get(pk=request.session['id'])
    except:
        err='Can\'t get your infomation '
    try:
        customer_obj=Members.objects.get(pk=cid)
    except:
        err+='Can\'t get the customer infomation'

    output={}
    if err!='':
        output['outhtml']=err
    else:
        try:
            have_in=Maillist.objects.get(members=customer_obj,sales=sales_obj)
            output['outhtml']='The customer has in mailing list'
        except:
            maillist_obj=Maillist(
            members=customer_obj,
            sales=sales_obj,
            addtime=datetime.datetime.now(),
            sendtime=datetime.datetime.now(),
            tomail=customer_obj.email,
            subject='',
            mailbody='',
            issend=1,
            )
            maillist_obj.save()
            output['outhtml']='Add success'
    #return HttpResponse('ok')
    return JsonResponse(output)

def onsending (request,mid):
    err=''
    output={}
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    try:
        mail_obj=Maillist.objects.get(pk=mid)
        mail_obj.issend=(mail_obj.issend+1)%2
        mail_obj.save()
        output['mid']=mid
        output['issend']=mail_obj.issend
    except:
        pass

    return JsonResponse(output)

def deletemail (request,mid):
    err=''
    output={}
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    try:
        Maillist.objects.filter(pk=mid).delete()
        output['mid']=mid
    except:
        pass
    return JsonResponse(output)


def saveeditmail (request):
    err=''
    output={}
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    if request.POST:

        newtomail=request.POST.get('newmail','')
        editmid=request.POST.get('editmid','')
        try:
            mail_obj=Maillist.objects.get(pk=editmid)
            mail_obj.tomail=newtomail
            mail_obj.save()
            output['mid']=editmid
            output['newtomail']=mail_obj.tomail
        except:
            pass
        return JsonResponse(output)

def maillist (request,page='1'):
    err=''
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    try:
        sales_obj=Salesperson.objects.get(pk=request.session['id'])
        sales_obj=Salesperson.objects.filter(group=request.session['group']) #filter sales group
    except:
        err='Can\'t get your infomation '
    try:
        mailfile=Mailfile.objects.get(automail=0,sales=sales_obj)
    except:
        mailfile=''
    mail_list=Maillist.objects.filter(sales=sales_obj).order_by("-id")

    paginator=Paginator(mail_list,200)

    try:
        page=int(page)
        curPage = paginator.page(page)
    except:
        return HttpResponseRedirect('/maillist/')

    return render_to_response('maillist.html',{
    'paginator':paginator,
    'mail_list':curPage.object_list,
    'is_paginated': paginator.num_pages > 1,
    'has_next': curPage.has_next(),
    'has_previous': curPage.has_previous(),
    'current_page': page,
    'next_page': page + 1,
    'previous_page': page - 1,
    'pages': paginator.num_pages,
    'page_numbers': range(paginator.num_pages+1)[1:],
    'hits' : paginator.count,
    'sales_obj':sales_obj,
    'mailfile':mailfile,
    })


#已成功发送的邮件
def sentmail (request,page='1'):
    err=''

    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    try:
        sales_obj=Salesperson.objects.get(pk=request.session['id'])
        sales_obj=Salesperson.objects.filter(group=request.session['group'])
    except:
        err='Can\'t get your infomation '
    if request.session['level']=="administrators":
        mail_list=Maillog.objects.filter(automail=0).order_by('-id')
    else:
        mail_list=Maillog.objects.filter(sales=sales_obj,automail=0).order_by('-id')


    paginator=Paginator(mail_list,20)

    try:
        page=int(page)
        curPage = paginator.page(page)
    except:
        return HttpResponseRedirect('/sentmail/')

    return render_to_response('sentmail.html',{
    'paginator':paginator,
    'mail_list':curPage.object_list,
    'is_paginated': paginator.num_pages > 1,
    'has_next': curPage.has_next(),
    'has_previous': curPage.has_previous(),
    'current_page': page,
    'next_page': page + 1,
    'previous_page': page - 1,
    'pages': paginator.num_pages,
    'page_numbers': range(paginator.num_pages+1)[1:],
    'hits' : paginator.count,
    'url':'sentmail',
    })

def autosentmail (request,page='1'):
    err=''
    try:
        request.session['id']
    except:
        return HttpResponseRedirect('/')
    try:
        sales_obj=Salesperson.objects.get(pk=request.session['id'])
        sales_obj=Salesperson.objects.filter(group=request.session['group'])
    except:
        err='Can\'t get your infomation '
    if request.session['level']=="administrators":
        mail_list=Maillog.objects.filter(automail=1).order_by('-id')
    else:
        mail_list=Maillog.objects.filter(sales=sales_obj,automail=1).order_by('-id')

    paginator=Paginator(mail_list,20)

    try:
        page=int(page)
        curPage = paginator.page(page)
    except:
        return HttpResponseRedirect('/autosentmail/')

    return render_to_response('sentmail.html',{
    'paginator':paginator,
    'mail_list':curPage.object_list,
    'is_paginated': paginator.num_pages > 1,
    'has_next': curPage.has_next(),
    'has_previous': curPage.has_previous(),
    'current_page': page,
    'next_page': page + 1,
    'previous_page': page - 1,
    'pages': paginator.num_pages,
    'page_numbers': range(paginator.num_pages+1)[1:],
    'hits' : paginator.count,
    'url':'autosentmail',
    })

#用于批量发送邮件.但函数调用一次只发一封
def sendthemail (request):
    err=''
    output={}
    try:
        request.session['id']
        sales_obj=Salesperson.objects.get(pk=request.session['id'])
        sales_obj=Salesperson.objects.filter(group=request.session['group'])
    except:
        return HttpResponseRedirect('/')
    if request.POST:
        frommail=request.POST.get('frommail','')
        subject=request.POST.get('subject','')
        content=request.POST.get('content','')
        #于数据库中查找一条EMAIL发送.发送成功的从此表删除.转移到记录表.不成功的作标识
        mail_list=Maillist.objects.filter(sales=sales_obj,issend=1)[:1]
        output['sendok']=0
        output['moremail']=0#是否AJAX循环继续发下一封
        for m in mail_list:
            output['moremail']=1
            try:
                authInfo = {}
                authInfo['server'] = settings.EMAIL_HOST
                authInfo['user'] = settings.EMAIL_HOST_USER #用户名
                authInfo['password'] = settings.EMAIL_HOST_PASSWORD #密码
                fromAdd = frommail  #邮箱地址
                toAdd = [m.tomail]
                subject = subject
                #files = ['urls.py']
                #files=''
                files=[]
                try:
                    mf_obj=Mailfile.objects.get(automail=0,sales=sales_obj)
                    fp=str(settings.WEB_ROOT)+mf_obj.fileurl
                    files.append(fp)
                except:
                    files=''
                #plainText = '这里是普通文本'
                htmlText = content.replace('\n', '<br />') or ''
                sendEmail(authInfo, fromAdd, toAdd, subject, files, htmlText)
                try:
                    m_obj=m.members
                except:
                    m_obj=Members(
                    id=0,
                    )
                #将此邮件入已发送库后删除.
                maillog_obj=Maillog(
                members=m_obj,
                sales=m.sales,
                addtime=m.addtime,
                sendtime=datetime.datetime.now(),
                tomail=m.tomail,
                subject=m.subject,
                mailbody=m.mailbody,
                dontsend=0,
                automail=0,
                )
                maillog_obj.save()
                #删
                Maillist.objects.filter(pk=m.id).delete()
                output['sendok']=1
            except:
                m.issend=0
                m.save()
            output['mid']=m.id
        return JsonResponse(output)

#保存附件
def mailfile (request):
    err=''
    output={}
    try:
        request.session['id']
        sales_obj=Salesperson.objects.get(pk=request.session['id'])
        sales_obj=Salesperson.objects.filter(group=request.session['group'])
    except:
        return HttpResponseRedirect('/')
    if request.POST:
        automail=request.POST.get('automail','0')
        tid=request.POST.get('tid','')
        file_obj=request.FILES.get('mailfile', None)
        saveok=0
        print tid
        if file_obj:
            print "-----------"
            from os.path import basename
            shellpath=str(settings.WEB_ROOT)
            filepath=shellpath+"/static/mailfile/"
            filepath=filepath.replace('//', '/')
            fileName=file_obj['filename']
            filetype=basename(fileName).split(".").pop().lower()
            fname="chinaedugrp_"+str(sales_obj.name)+"_mt"
            im=file(filepath+str(fname)+'.'+filetype,'wb')
            fileurl_value="/static/mailfile/"+str(fname)+'.'+filetype
            im.write(request.FILES.get('mailfile')['content'])
            im.close()
            #入库
            try:
                mf_obj=Mailfile.objects.get(automail=0,sales=sales_obj)
                c='rm '+shellpath+str(mf_obj.fileurl)
                os.system(c)
                mf_obj.fileurl=fileurl_value
            except:
                mf_obj=Mailfile(
                sales=sales_obj,
                project_id=0,
                title='',
                fileurl=fileurl_value,
                automail=automail,
                )
            mf_obj.save()
            saveok=1
            output['mf_url']=fileurl_value
        output['saveok']=saveok

    return HttpResponseRedirect('/maillist/')


def delfile (request):
    err=''
    output={}
    try:
        request.session['id']
        sales_obj=Salesperson.objects.get(pk=request.session['id'])
        sales_obj=Salesperson.objects.filter(group=request.session['group'])
    except:
        return HttpResponseRedirect('/')
    if request.POST:
        ma=request.POST.get('ma','')
        output['delok']=0
        if ma=='m':
            try:
                from os.path import basename
                shellpath=str(settings.WEB_ROOT)
                m_obj=Mailfile.objects.get(automail=0,sales=sales_obj)
                c='rm '+shellpath+str(m_obj.fileurl)
                os.system(c)
            except:
                pass
            try:
                Mailfile.objects.filter(automail=0,sales=sales_obj).delete()
                output['delok']=1
            except:
                pass
        if ma=='a':
            try:
                from os.path import basename
                shellpath=str(settings.WEB_ROOT)
                m_obj=Mailfile.objects.get(automail=1,sales=sales_obj)
                c='rm '+shellpath+str(m_obj.fileurl)
                os.system(c)
            except:
                pass
            try:
                Mailfile.objects.filter(automail=1,sales=sales_obj).delete()
                output['delok']=1
            except:
                pass
        return JsonResponse(output)

def sendEmail(authInfo, fromAdd, toAdd, subject,files, htmlText):

    strFrom = fromAdd
    strTo = ', '.join(toAdd)

    server = authInfo.get('server')
    user = authInfo.get('user')
    passwd = authInfo.get('password')

    if not (server and user and passwd) :
            print 'incomplete login info, exit now'
            return

    # 设定root信息
    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = subject
    msgRoot['From'] = strFrom
    msgRoot['To'] = strTo
    msgRoot.preamble = 'This is a multi-part message in MIME format.'

    # Encapsulate the plain and HTML versions of the message body in an
    # 'alternative' part, so message agents can decide which they want to display.
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

#    #设定纯文本信息
#    msgText = MIMEText(plainText, 'plain', 'utf-8')
#    msgAlternative.attach(msgText)

    #设定HTML信息
    msgText = MIMEText(htmlText, 'html', 'utf-8')
    msgAlternative.attach(msgText)

    #设定附件信息
    for file in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(file,"rb").read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
        msgAlternative.attach(part)

    #发送邮件
    smtp = smtplib.SMTP()
    #设定调试级别，依情况而定
    smtp.set_debuglevel(1)
    smtp.connect(server)
    smtp.login(user, passwd)
    smtp.sendmail(strFrom, strTo, msgRoot.as_string())
    smtp.quit()
    return











